package com.pingbu.tijian.hospital.backapi.service;


import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.pingbu.common.bean.ResultBean;
import com.pingbu.common.utils.PbSecretUtils;
import com.pingbu.tijian.hospital.backapi.bean.entity.*;
import com.pingbu.tijian.hospital.backapi.config.GlobalConst;
import com.pingbu.tijian.hospital.backapi.mapper.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.regexp.RE;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class ClassesService {

    private static Logger logger = LoggerFactory.getLogger(ClassesService.class);


    @Autowired
    private ClassesMapper classesMapper;
    @Autowired
    private ClassStudentMapper classStudentMapper;
    @Autowired
    private StudentMapper studentMapper;
    @Autowired
    private UserInfoMapper userInfoMapper;
    @Autowired
    private UserPermissionMapper userPermissionMapper;

    @Autowired
    private JoinClassMessageMapper joinClassMessageMapper;

    public ResultBean<Classes> add(Classes param) {

        param.setNoid(PbSecretUtils.uuid());

        param.setClass_code(PbSecretUtils.uuid().substring(0, 8));

        if(param.getClass_name() == null){
            return ResultBean.create(20,"班级名称不能为空");
        }

        if(param.getClass_state() == null){
            return ResultBean.create(20,"班级状态不能为空");
        }

        try {
            classesMapper.insert(param);
        } catch (Exception err) {
            return ResultBean.create(23, err.getMessage());
        }
        return ResultBean.create(0, "success", param);
    }

    /**
     * 修改班级
     *
     * @param param
     * @return
     */
    public ResultBean<Classes> edit(Classes param) {
        try {
            param.setClass_code(PbSecretUtils.uuid().substring(0, 8));
            classesMapper.update(param);
        } catch (Exception err) {
            return ResultBean.create(23, err.getMessage());
        }
        return ResultBean.create(0, "success", param);
    }

    /**
     * 获取班级列表
     *
     * @param param
     * @return
     */
    public ResultBean<List<Classes>> list(UserInfo param) {
        Classes classes = new Classes();
        List<Classes> classList = classesMapper.list(classes);
        return ResultBean.create(0, "success", classList);
    }

    /**
     * 班级分页
     *
     * @param param
     * @return
     */
    public ResultBean<PageInfo<Classes>> page(Classes param) {
        //先拿到一次满足searkey条件的记录
        List<Classes> lst3 = classesMapper.list(param);
        //当前页-1*12
        int countNumb = (param.getPageNum() - 1) * param.getPageSize();

        //判断搜索条件不为null lst3的长度<=当前的页数-1*12
        if (param.getSearchKey() != null && !"".equals(param.getSearchKey()) && lst3.size() <= countNumb) {
            param.setPageNum(1);
        }

        PageHelper.startPage(param.getPageNum(), param.getPageSize());
        List<Classes> list = classesMapper.list(param);
        //查看该班级下是否存在学生
        for (Classes classes : list) {
            ClassStudent classStudent = new ClassStudent();
            classStudent.setClass_noid(classes.getNoid());

            List<ClassStudent> classStudentList = classStudentMapper.list(classStudent);
            List<Student> students = new ArrayList<>();
            for (ClassStudent student : classStudentList) {
                Student student1 = new Student();
                student1.setNoid(student.getStudent_noid());
                Student stu2 = studentMapper.get(student1);
                students.add(stu2);
            }
//            classes.setStudentList(students);
        }
        PageInfo<Classes> pi1 = new PageInfo<>(list);
        PageHelper.clearPage();
        return ResultBean.create(0, "success", pi1);
    }

    /**
     * 删除班级
     *
     * @param param
     * @return
     */
    public ResultBean<Integer> delete(Classes param) {
        try {
            classesMapper.delete(param);
        } catch (Exception err) {
            return ResultBean.create(23, err.getMessage());
        }
        return ResultBean.create(0, "success", 0);
    }

    /**
     * 保存学生到班级
     *
     * @param param
     * @return
     */
    public ResultBean<Integer> saveStudents(Classes param) {
        try {
            ClassStudent classStudent = new ClassStudent();
            classStudent.setClass_noid(param.getNoid());
            classStudentMapper.delete(classStudent);
            if (param.getStudentsNoid().length != 0) {
                for (int i = 0; i < param.getStudentsNoid().length; i++) {
                    classStudent.setNoid(PbSecretUtils.uuid());
                    classStudent.setStudent_noid(param.getStudentsNoid()[i]);
                    //根据要添加的student_noid与class_noid在t_class_student是否有这条记录
                    ClassStudent getClassStudent = classStudentMapper.get(classStudent);
                    //如果没有就新增
                    if (getClassStudent == null) {
                        classStudentMapper.insert(classStudent);
                    }
                }
            }
        } catch (Exception err) {
            return ResultBean.create(23, err.getMessage());
        }
        return ResultBean.create(0, "success", 0);
    }

    /**
     * 获取当前班级的所有学生
     *
     * @param param
     * @return
     */
    public ResultBean<List<ClassStudent>> currentStudents(ClassStudent param) {
        List<ClassStudent> currentStudentsList = classStudentMapper.list(param);
        return ResultBean.create(0, "success", currentStudentsList);
    }

    /**
     * 切换班级
     *
     * @param param
     * @return
     */
    public ResultBean<Integer> defaultClass(UserInfo param) {
        UserInfo userInfo = new UserInfo();
        userInfo.setUsercode(param.getUsercode());
        UserInfo user = userInfoMapper.get(userInfo);
        try {
            userInfoMapper.update(param);
        } catch (Exception err) {
            return ResultBean.create(23, err.getMessage());
        }
        Classes classes = new Classes();
        classes.setNoid(user.getDefault_class_noid());
        Classes getClass = classesMapper.get(classes);
        return ResultBean.create(0, "success", getClass);
    }

    /**
     * @Description:根据classCode判断这个班级码是否已经存在
     * @Param classes中的classCode
     * @Return:true表示该班级已经存在, false表示该班级不存在
     * @Creator: Rubbish Sen
     * @CreatorTime: 2021/11/30
     */
    public Boolean classCodeIsExit(Classes classes) {
        Classes classes1 = classesMapper.byClassCodeGetClass(classes);

        if (classes1 != null) {
            return true;
        }
        return false;
    }

    /**
     * 获取当前用户所在的班级
     *
     * @param param
     * @return
     */
    public ResultBean<Classes> getCurrenClass(UserInfo param) {
        UserInfo userInfo = userInfoMapper.get(param);
        Classes classes = new Classes();
        classes.setNoid(userInfo.getDefault_class_noid());
        Classes getClass = new Classes();
        if (!StringUtils.isEmpty(classes.getNoid())) {
            getClass = classesMapper.get(classes);
        } else {
            Student s1 = new Student();
            s1.setBind_usercode(userInfo.getUsercode());
            Student s2 = studentMapper.get(s1);
            ClassStudent classStudent = new ClassStudent();
            classStudent.setStudent_noid(s2.getNoid());
            ClassStudent cs2 = classStudentMapper.get(classStudent);
            Classes classes1 = new Classes();
            classes1.setNoid(cs2.getClass_noid());
            getClass = classesMapper.get(classes1);
        }
        return ResultBean.create(0, "success", getClass);
    }

    /**
     * @Description:用户输入班级码来加入班级,并且需要在消息库中新建一条班级申请消息
     * @Param classes
     * @Return: com.pingbu.common.bean.ResultBean<java.lang.Integer>
     * @CreatorTime: 2021/11/30
     */
    public ResultBean<Integer> UserJoinClass(UserInfo param, Classes classes) {
        //首先判断这个班级码是否是存在的
        Boolean aBoolean = classCodeIsExit(classes);
        //如果不存在的话则直接进行返回
        if (aBoolean == false) {
            return ResultBean.create(43, "出现异常,没有查询到该班级");
        }
        //查询该学生所在的班级下是否已经有这个学生
        Classes classes1 = classesMapper.byClassCodeGetClass(classes);
        //去查询该班级下所有的学生,得到所有的学生id
        List<String> classStudentId = classesMapper.getClassStudentId(classes1.getNoid());
        System.out.println("该班级下学生的id");
        for (String stuId:classStudentId) {
            System.out.println(stuId);
            //判断该班级中是否已经存在该学生
            if (param.getNoid().equals(stuId)){
                System.out.println("进来了!");
                return ResultBean.create(43, "出现异常,你已经在该班级中了!不能再重复添加");
            }
        }
        /*
        *
        *
        * 向该班级码的创建者发送加入班级的请求信息:暂时未完成
        *
        *
        *
        * */
        String uuid = PbSecretUtils.uuid();
        JoinClassMessage joinClassMessage = new JoinClassMessage(uuid,param.getNoid(),classes.getClass_code(),null);

        System.out.println(joinClassMessage);

        joinClassMessageMapper.addJoinClassMessage(joinClassMessage);

        return ResultBean.create(0, "success");
    }

    /**
     * 获取当前用户所在的所有班级
     * @param param
     * @return
     */
    public ResultBean<Classes> getUserInfoClasses(UserInfo param) {
        Student student = new Student();
        student.setBind_usercode(param.getUsercode());
        Student student1 = studentMapper.get(student);
        if (student1 != null) {
            ClassStudent classStudent  = new ClassStudent();
            classStudent.setStudent_noid(student1.getNoid());
            //得到学生对应的所有班级id
            List<ClassStudent> classStudentList = classStudentMapper.list(classStudent);
            //转换班级id为班级
            List<Classes> classesList = new ArrayList<>();
            for (ClassStudent classStudent1 : classStudentList) {
                Classes classes = new Classes();
                classes.setNoid(classStudent1.getClass_noid());
                Classes classes1 = classesMapper.byClassCodeGetClass(classes);
                classesList.add(classes1);
            }
            return ResultBean.create(0, "success", classesList);
        } else {
            return ResultBean.create(10, "当前用户所对应的学生不存在！", null);
        }
    }

    public ResultBean<Classes> searchClasses(Classes param) {
        Classes classes = classesMapper.get(param);
        return ResultBean.create(0, "success", classes);
    }
}
